//
//  HACMLineNode.m
//  HStockCharts
//
//  Created by Hotacool on 2018/10/9.
//

#import "HACMLineNode.h"
#import "HACTimeLineEntry.h"
#import "HACHaloLayer.h"
#import "HACPainter.h"

NSString* const HACTimeLineViewAVGDataLabel = @"HACMLineAvgData";
static NSString * const HACMLineNodeDealFormat = @"成交均价:%.2f";
@interface HACMLineNode ()
@property (nonatomic, strong) HACHaloLayer *haloLayer;//最后一点动画
@property (nonatomic, assign) CGPoint latestPoint;//记录最后更新的一点

/** 画笔：成交均价label */
@property (nonatomic, strong) HACTextPainter *textPainter;
@end

@implementation HACMLineNode {
    NSTimer *_haloTimer;
    HACPointEntry *_avgPoint;
}

- (void)dealloc {
    [self activeHaloTimer:NO];
}

- (void)setData:(HACChartData *)data {
    [super setData:data];
    HACChartDataSet *tmp = [data dataSetWithLabel:HACBasicDataLabel];
    self.basicInfoData = tmp?(HACBasicInfoEntry*)tmp.values.firstObject:nil;
    tmp = [data dataSetWithLabel:HACTimeLineViewAVGDataLabel];
    if (tmp.values.count > 0) {
        _avgPoint = tmp.values.firstObject;
    } else {
        _avgPoint = nil;
    }
}

- (void)setUp {
    [super setUp];
    self.isCenter = YES;//点居中，考虑到指标对齐
}

- (HACTextPainter *)textPainter {
    if (!_textPainter) {
        _textPainter = [HACTextPainter painterLayer];
        _textPainter.zPosition = 999;
        _textPainter.anchorPoint = CGPointMake(0, 0);
        _textPainter.contentsScale = [UIScreen mainScreen].scale;
        _textPainter.foregroundColor = RGB_HEX(kRedColor).CGColor;
        _textPainter.font = (__bridge CFTypeRef _Nullable)([UIFont systemFontOfSize:kAxisTextFontSize]);
        _textPainter.fontSize = kAxisTextFontSize;
    }
    return _textPainter;
}

- (void)setNeedsDisplay {
    [super setNeedsDisplay];
    //推送点动画效果
    CGPoint newPoint = [self pointAtChartForIndex:self.visualCount];
    if (!CGPointEqualToPoint(self.latestPoint, newPoint)) {
        self.latestPoint = newPoint;
        self.haloLayer.hidden = NO;
        [self.haloLayer setupPosition:CGPointMake(newPoint.x, newPoint.y)];
        [self activeHaloTimer:YES];
    }
    
    if (_avgPoint) {
        long digits = self.basicInfoData.priceDigits!=0?self.basicInfoData.priceDigits:0;
        NSString *text = [NSString stringWithFormat:HACMLineNodeDealFormat, _avgPoint.y/pow(10, digits)];
        self.textPainter.string = text;
        CGSize size = [text boundingRectWithSize:CGSizeMake(self.relativeFrame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:kAxisTextFontSize]} context:nil].size;
        self.textPainter.bounds = (CGRect){{0,0},size};
        CGFloat value = [self lineValueForItem:(HACTimeLineEntry*)_avgPoint lineIndex:0];
        CGFloat y = [self calculatorYForValue:value min:self.minValue max:self.maxValue inRect:self.pointRect];
        if (self.actualCount <= self.visualCount / 2) {
            self.textPainter.position = CGPointMake(0, y - size.height - 2);
        } else {
            self.textPainter.position = CGPointMake(self.relativeFrame.size.width - size.width - 4, y - size.height - 2);
        }
        [self.textPainter paintInLayer:self.hostLayer];
    }
}

- (HACHaloLayer *)haloLayer {
    if (!_haloLayer) {
        _haloLayer = [HACHaloLayer layer];
        _haloLayer.radius = 3.0;
        _haloLayer.backgroundColor = RGB_HEX(kMLineColor).CGColor;
        _haloLayer.opacity = 0.8;
        _haloLayer.hidden = YES;
        [self.hostLayer addSublayer:_haloLayer];
    }
    return _haloLayer;
}

#pragma mark -- animation timer
- (void)activeHaloTimer:(BOOL)isActive {
    if (_haloTimer) {
        [_haloTimer invalidate];
        _haloTimer = nil;
    }
    if (isActive) {
        _haloTimer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(timerFire:) userInfo:nil repeats:NO];
        [[NSRunLoop mainRunLoop] addTimer:_haloTimer forMode:NSRunLoopCommonModes];
    }
}

- (void)timerFire:(NSTimer*)timer {
    self.haloLayer.hidden = YES;
}

#pragma mark --
- (CGFloat)lineValueForItem:(HACTimeLineEntry *)data lineIndex:(NSInteger)index {
    if ([data isKindOfClass:[HACTimeLineEntry class]]) {
        return data.newprice;
    } else if ([data isKindOfClass:[HACPointEntry class]]) {
        return ((HACPointEntry*)data).y;
    }
    return 0.0;
}

// 计算最大，最小值
- (void)calculateLimitValue {
    CGFloat __block max = FLT_MIN;
    CGFloat __block min = FLT_MAX;
    [self.lineDicData enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, NSArray * _Nonnull obj, BOOL * _Nonnull stop) {
        long start = self.startIndex;
        long len = self.endIndex - self.startIndex + 1;
        if (start+len>self.actualCount) {
            len = self.actualCount - start;
        }
        if (obj.count>0) {//加判断：防止因数据错误导致的crash
            if (start>=obj.count) {
                start = obj.count-1;
                len = 1;
            }else{
                if (start+len>obj.count) {
                    len = obj.count - start;
                }
            }
            obj = [obj subarrayWithRange:NSMakeRange(start, len)];
        }
        for (id p in obj) {
            CGFloat value = [self lineValueForItem:p lineIndex:0];
            if (value == kDrawingInvaildValue) {
                continue;
            }
            if (value > max) {
                max = value;
            }
            if (value < min) {
                min = value;
            }
        }
    }];
    self.maxValue = (max == FLT_MIN) ? .0 : max;
    self.minValue = (min == FLT_MAX) ? .0 : min;
    
    //调整位置
    if (self.basicInfoData&&self.maxValue!=0&&self.minValue!=0) {
        float base = self.basicInfoData.dpreviousPrice;
        float a = ABS(self.maxValue - base);
        float b = ABS(base - self.minValue);
        if (base > self.maxValue) {
            self.maxValue = base + b;
        } else if (base < self.minValue) {
            self.minValue = base - a;
        } else {
            if (a > b) {
                self.minValue = base - a;
            } else {
                self.maxValue = base + b;
            }
        }
    }
}
@end
